package org.example.util;



import java.sql.*;
import java.util.ResourceBundle;

    // 数据库操作工具类
public class DButil{

        private static final String driver;
        private static final String url;
        private static final String user;
        private static final String pwd;


        static {
            ResourceBundle bundle = ResourceBundle.getBundle("mysql");

            driver = bundle.getString("driver");
            url = bundle.getString("url");
            user = bundle.getString("user");
            pwd = bundle.getString("password");
        }

        public static Connection getConnection() throws RuntimeException {
            Connection connection=null;
            try {
                Class.forName(driver).newInstance();
                connection = DriverManager.getConnection(url, user, pwd);
            } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return connection;
        }

        public static void closeResultSet(ResultSet resultSet){
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public static void closeStatement(Statement statement){
            if (statement != null){

                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public static void closeConnection(Connection connection){
            if (connection != null){

                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }


        public static void close(ResultSet resultSet, Statement statement, Connection connection){
            closeResultSet(resultSet);
            closeStatement(statement);
            closeConnection(connection);
        }
    }

